// 加密公共封装工具类
import CryptoJS from 'crypto-js'
import uuidv1 from 'uuid/v1'
import $ from '../../static/js/jquery-1.12.4.min'
import Version from '@/common/version'
import api from '@/common/config/api'
import tools from '@/utils/tools'

// ## WEB 加密参数配置 start
const VUE_APP_WEB_APP_VERSION = Version.version
// #获取iv值得配置
// # key
const VUE_APP_IV_KEY_VALUE = 'yPqu5cdmNmtpKbsq'
// # iv
const VUE_APP_IV_VALUE = 'yPqu5cdmNmtpKbsq'
// # 获取iv数据的地址
const VUE_APP_IV_URL = api.getApiIv
// # 加密 key值
const VUE_APP_CRYPTOJS_KEY = 'GAFymnq64OvRe70M'
// ## WEB 加密参数配置 end

//十六位十六进制数作为密钥
const key = CryptoJS.enc.Utf8.parse(VUE_APP_CRYPTOJS_KEY)

function localGet (key) {
  return localStorage.getItem(key)
}
function localSet (key, val) {
  localStorage.setItem(key, val)
}

function getUUID (len) {
  return uuidv1().replace(/-/g, '')
}

// 初始化方法 ，不能使用axios请求，不然进入死循环请求key和value
// eslint-disable-next-line no-unused-vars
// 类型 0 获取iv 1 返回配置文件中得iv值
function initIvValue (type) {
  if ('1' === type) {
    return VUE_APP_IV_VALUE
  } else if ('0' === type) {
    let ivValueEn = localGet('CRYPTOJS_IV')
    if (ivValueEn == '' || ivValueEn == null || ivValueEn == undefined) {
      let ivUrl = VUE_APP_IV_URL
      $.ajax({
        url: ivUrl,
        type: 'post',
        async: false,//使用同步的方式,true为异步方式
        success: function (data) {
          if (data.code === 0) {
            localSet('CRYPTOJS_IV', data.message)
            ivValueEn = data.message
          } else {
            tools.tip(data.message || '网络异常')
          }
        },
        error: function () {
          tools.tip('网络异常')
        }
      })
    }
    return DecryptIv(ivValueEn, '1')
  } else {
    return ''
  }
}

//对请求之后的iv解密方法
// eslint-disable-next-line no-unused-vars
function DecryptIv (word, type) {
  let lvString = initIvValue(type)
  // "",null,undefined
  if (lvString != '') {
    let iv = CryptoJS.enc.Utf8.parse(lvString)
    let ivKey = CryptoJS.enc.Utf8.parse(VUE_APP_IV_KEY_VALUE)
    let decrypted = CryptoJS.AES.decrypt(word, ivKey, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })
    return decrypted.toString(CryptoJS.enc.Utf8)
  }
}

//解密方法
function Decrypt (word, type) {
  let lvString = initIvValue(type)
  // "",null,undefined
  if (lvString != '' || lvString != null || lvString != undefined) {
    let iv = CryptoJS.enc.Utf8.parse(lvString)
    let decrypted = CryptoJS.AES.decrypt(word, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })
    return decrypted.toString(CryptoJS.enc.Utf8)
  }
}

//加密方法
function Encrypt (word) {
  // console.info('key-------'+VUE_APP_CRYPTOJS_KEY)
  // console.info('iv-------'+VUE_APP_CRYPTOJS_IV)
  // console.info('待加密的字符串为-------'+word)
  let lvString = initIvValue('0')
  // // "",null,undefined
  if (lvString != '' || lvString != null || lvString != undefined) {
    let iv = CryptoJS.enc.Utf8.parse(lvString)
    let encrypted = CryptoJS.AES.encrypt(word, key, {iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7})
    // console.info('BASE64加密的字符串-------'+encrypted.toString())
    return encrypted.toString()
  } else {
    tools.tip('获取lv错误')
  }
}

function EncryptMd5 (word) {
  // console.info('MD5加密后的字符串-------'+CryptoJS.MD5(word).toString())
  return CryptoJS.MD5(CryptoJS.MD5(word).toString())
}

//生成加密后的url--get
function EncryptUrl (url) {
  // console.info('待封装的url-------'+url)
  // console.info('key-------'+VUE_APP_CRYPTOJS_KEY)
  // console.info('iv-------'+VUE_APP_CRYPTOJS_IV)

  let uuid = getUUID()
  let timestamp = new Date().getTime()
  let encrypted = Encrypt(uuid + timestamp)
  let version = VUE_APP_WEB_APP_VERSION
  // console.info('BASE64加密的字符串-------'+encrypted.toString())

  let sign = EncryptMd5(encrypted.toString())

  if (url.indexOf('?') != -1) {
    // 有参数
    let query = '&uuid='
    query += uuid
    query += '&timestamp='
    query += timestamp
    query += '&sign='
    query += sign
    query += '&version='
    query += version
    return url + query
  } else {
    // 无参数
    let query = '?uuid='
    query += uuid
    query += '&timestamp='
    query += timestamp
    query += '&sign='
    query += sign
    query += '&version='
    query += version
    return url + query
  }
}

export default {
  Decrypt,
  Encrypt,
  EncryptMd5,
  EncryptUrl,
  getUUID
}
